"""自由使用的MySql工具!!  Freedam日志模块"""

import logging
import os
import datetime
import threading

class Logger:
    """日志记录器类"""
    
    _instance = None
    _lock = threading.Lock()
    
    def __new__(cls):
        """单例模式创建日志记录器"""
        with cls._lock:
            if cls._instance is None:
                cls._instance = super(Logger, cls).__new__(cls)
                cls._instance._init_logger()
            return cls._instance
    
    def _init_logger(self):
        """初始化日志记录器"""
        # 创建日志目录
        log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'logs')
        if not os.path.exists(log_dir):
            os.makedirs(log_dir)
        
        # 设置日志文件名称（按日期）
        today = datetime.date.today()
        log_file = os.path.join(log_dir, f'mysqlpass_{today.strftime("%Y%m%d")}.log')
        
        # 创建logger对象
        self.logger = logging.getLogger('mysqlpass')
        self.logger.setLevel(logging.DEBUG)
        
        # 检查是否已经添加了handler
        if not self.logger.handlers:
            # 创建file handler
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(logging.DEBUG)
            
            # 创建console handler
            console_handler = logging.StreamHandler()
            console_handler.setLevel(logging.INFO)
            
            # 设置日志格式
            formatter = logging.Formatter('%(asctime)s - %(threadName)s - %(levelname)s - %(message)s')
            file_handler.setFormatter(formatter)
            console_handler.setFormatter(formatter)
            
            # 添加handler到logger
            self.logger.addHandler(file_handler)
            self.logger.addHandler(console_handler)
    
    def debug(self, message):
        """记录调试信息"""
        self.logger.debug(message)
    
    def info(self, message):
        """记录普通信息"""
        self.logger.info(message)
    
    def warning(self, message):
        """记录警告信息"""
        self.logger.warning(message)
    
    def error(self, message):
        """记录错误信息"""
        self.logger.error(message)
    
    def critical(self, message):
        """记录严重错误信息"""
        self.logger.critical(message)
    
    def exception(self, message):
        """记录异常信息"""
        self.logger.exception(message)

# 创建全局日志记录器实例
logger = Logger()

# 导出常用日志方法
debug = logger.debug
info = logger.info
warning = logger.warning
error = logger.error
critical = logger.critical
exception = logger.exception